//
//  SCEmoticonCell.swift
//  weibo
//
//  Created by 阿城 on 15/12/17.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit

class SCEmoticonCell: UICollectionViewCell {
    var dataList: [SCEmoticonModel]?{
        didSet{
            for i in 0..<20 {
                //是否越界
                if i < dataList!.count{
                    buttonArr[i].emoticon = dataList![i]
                }else{
                    buttonArr[i].emoticon = nil
                }
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundView = UIImageView(image: UIImage(named: "emoticon_keyboard_background"))
        
        //        addSubview(lab)
        //        lab.snp_makeConstraints { (make) -> Void in
        //            make.center.equalTo(self)
        //        }
        addSubview(deleteBtn)
        addSubview(resentLab)
        resentLab.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-10)
        }
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let margin: CGFloat = 5
        let bottomMargin: CGFloat = 25
        let pageCol = 7
        let pageRow = 3
        let btnW = (width - margin * 2) / CGFloat(pageCol)
        let btnH = (height - bottomMargin) / CGFloat(pageRow)
        for i in 0..<20 {
            let col = i % pageCol
            let row = i / pageCol
            let btnX = CGFloat(col) * btnW + margin
            let btnY = CGFloat(row) * btnH
            buttonArr[i].frame = CGRect(x: btnX, y: btnY, width: btnW, height: btnH)
        }
        
        deleteBtn.frame = CGRect(x: 6 * btnW + margin, y: 2 * btnH, width: btnW, height: btnH)
    }
    
    //删除按钮
    private lazy var deleteBtn: UIButton = {
        
        let btn = UIButton()
        btn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        btn.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
        
    }()
    
    //emoticon按钮
    private lazy var buttonArr: [SCEmoticonButton] = {
        var btns = [SCEmoticonButton]()
        for _ in 0..<20{
            let btn = SCEmoticonButton()
            btns.append(btn)
            self.contentView.addSubview(btn)
            //添加点击事件
            btn.addTarget(self, action: "emoticonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            //添加手势
            let longPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
            longPress.minimumPressDuration = 0.25
            btn.addGestureRecognizer(longPress)
            
        }
        return btns
    }()
    
    //处理长按逻辑
    @objc private func longPress(gesture: UILongPressGestureRecognizer){
        //        printLog(gesture)
        let currentPoint = gesture.locationInView(contentView)
        //        printLog(currentPoint)
        
        switch gesture.state {
        case .Began:
            contentView.addSubview(detailBg)
            displayDetailBG(gesture.view as! SCEmoticonButton)
        case .Changed:
            for btn in buttonArr where !btn.hidden{
                //辨别点在哪个按钮上
                if CGRectContainsPoint(btn.frame, currentPoint) {
                    detailBg.hidden = false
                    displayDetailBG(btn)
                    break
                }else{
                    detailBg.hidden = true
                }
            }
        case .Ended, .Cancelled:
            if !detailBg.hidden{
                emoticonClick(detailBg.showBtn!)
            }
            detailBg.removeFromSuperview()
            lastShowEmoji = nil
        default:
            break
        }
    }
    
    //纪录前一个选中的emoticon
    private var lastShowEmoji: SCEmoticonButton?
    
    //展示详细视图
    private func displayDetailBG(currentButton: SCEmoticonButton){
        
        if lastShowEmoji != currentButton{
            detailBg.center = currentButton.center
            detailBg.showBtn = currentButton
            lastShowEmoji = currentButton
        }
    }
    
    // MARK: - 按钮点击事件
    //emoticon点击事件
    @objc private func emoticonClick(button: SCEmoticonButton){
        NSNotificationCenter.defaultCenter().postNotificationName(kEmoticonNotification, object: button)
        
        //保存最近使用
        SCEmoticonViewModel.shareEmoticons.saveTheResent(button)
    }
    
    @objc private func deleteButtonClick(){
        NSNotificationCenter.defaultCenter().postNotificationName(kEmoticonNotification, object: nil)
    }
    
    
    lazy var lab: UILabel = UILabel(titleText: "", fontSize: 40)
    lazy var resentLab: UILabel = UILabel(titleText: "最近使用",color:UIColor.darkGrayColor(), fontSize: 14)
    private lazy var detailBg: SCDetailEmoticon = SCDetailEmoticon(frame: CGRectZero)
}


// MARK: - 表情按钮
class SCEmoticonButton: UIButton {
    var emoticon: SCEmoticonModel?{
        didSet{
    
            if let path = emoticon?.path {
                //emoticon
                setImage(UIImage(contentsOfFile: path), forState: UIControlState.Normal)
                setTitle(nil, forState: UIControlState.Normal)
                hidden = false
            }else if let code = emoticon?.code {
                //emoji
                let emoji = (code as NSString).emoji()
                setTitle(emoji, forState: UIControlState.Normal)
                setImage(nil, forState: UIControlState.Normal)
                hidden = false
            }else{
                //空
                setTitle(nil, forState: UIControlState.Normal)
                setImage(nil, forState: UIControlState.Normal)
                hidden = true
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        titleLabel?.font = UIFont.systemFontOfSize(34)
        adjustsImageWhenHighlighted = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

